import logging
import os
from logging.handlers import TimedRotatingFileHandler
from pythonjsonlogger import jsonlogger
from typing import Optional
from myUtils.config import settings

import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()
log_setting= settings.LogSettings
log_type = log_setting.log_type

class LoggerFactory:
    _instance = None
    _loggers = {}

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(LoggerFactory, cls).__new__(cls)
        return cls._instance

    @staticmethod
    def get_logger(name: Optional[str] = None,
                   log_dir: str = "logs") -> logging.Logger:
        """
        获取或创建logger实例
        :param name: logger名称
        :param log_dir: 日志目录
        :return: logger实例
        """
        logger_name = name or __name__
        if logger_name in LoggerFactory._loggers:
            return LoggerFactory._loggers[logger_name]

        logger = logging.getLogger(logger_name)

        # 避免重复添加处理器
        if logger.handlers:
            return logger

        # 确保日志目录存在
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        # 定义日志级别配置
        log_levels = {
            'debug': (logging.DEBUG, 7),
            'info': (logging.INFO, 30),
            'warning': (logging.WARNING, 30),
            'error': (logging.ERROR, 90)
        }
        logger.setLevel(logging.INFO)

        # 创建格式化器
        fmt='%(asctime)s %(levelname)s %(name)s %(lineno)d %(message)s'
        datefmt = '%Y-%m-%d %H:%M:%S'
        if log_type == 'json':
            formatter = jsonlogger.JsonFormatter(
                fmt=fmt,
                datefmt=datefmt,
                json_ensure_ascii=False)
        else:
            formatter = logging.Formatter(
                fmt=fmt,
                datefmt=datefmt)

        # 为每个级别创建处理器
        for level_name, (level, backup_count) in log_levels.items():
            file_handler = TimedRotatingFileHandler(filename=os.path.join(
                log_dir, f'app_{level_name}.log'),
                                                    when='midnight',
                                                    interval=1,
                                                    backupCount=backup_count,
                                                    encoding='utf-8')
            file_handler.setLevel(level)
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)

        # 添加控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(
            logging.Formatter(
                '%(asctime)s|%(levelname)-5s|%(filename)s:%(lineno)d|%(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'))
        logger.addHandler(console_handler)

        LoggerFactory._loggers[logger_name] = logger
        return logger


def setup_logger(
    name: Optional[str] = None,
    log_dir: str = log_setting.log_dir
) -> logging.Logger:
    """
    设置并返回logger实例的便捷函数
    """

    return LoggerFactory().get_logger(name, log_dir)
